﻿using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class DocumentRule : ILRule<DocumentHandle>
    {
        [ILInfo(true)]
        public byte[] Name { get; }

        [ILInfo]
        public Guid HashAlgorithm { get; }

        [ILInfo]
        public byte[] Hash { get; }

        [ILInfo]
        public Guid Language { get; }

        public DocumentRule(
            byte[] name,
            Guid hashAlgorithm,
            byte[] hash,
            Guid language)
            : base()
        {
            Name = name;
            HashAlgorithm = hashAlgorithm;
            Hash = hash;
            Language = language;
        }

        public DocumentRule(MetadataReader reader, DocumentHandle documentHandle)
            : base(reader)
        {
            Document document = reader.GetDocument(documentHandle);
            Name = reader.GetBlobBytes(document.Name);
            HashAlgorithm = reader.GetGuid(document.HashAlgorithm);
            Hash = reader.GetBlobBytes(document.Hash);
            Language = reader.GetGuid(document.Language);
        }

        public override DocumentHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddDocument(
                name: Name == null ? default : builder.GetOrAddBlob(Name),
                hashAlgorithm: builder.GetOrAddGuid(HashAlgorithm),
                hash: Hash == null ? default : builder.GetOrAddBlob(Hash),
                language: builder.GetOrAddGuid(Language));
        }
    }
}